package com.qiwx.pigeon.Utils;

import android.content.ContentValues;
import android.text.TextUtils;

import com.qiwx.pigeon.R;
import com.qiwx.pigeon.R2;
import com.qiwx.pigeon.app.AppContext;
import com.qiwx.pigeon.base.Constant;
import com.qiwx.pigeon.data.CageStatusConfig;
import com.qiwx.pigeon.data.db.CageModel;
import com.qiwx.pigeon.data.db.CageRecordModel;
import com.qiwx.pigeon.data.db.CageStatusRecord;
import com.qiwx.pigeon.data.db.SummaryFertilizeModel;
import com.qiwx.pigeon.data.db.SummaryNoEggModel;
import com.qiwx.pigeon.data.db.SummaryPigeonCKModel;
import com.qiwx.pigeon.data.db.SummaryPigeonDeathModel;
import com.qiwx.pigeon.data.db.WareHouseModel;
import com.qiwx.pigeon.data.vo.WareHouseBean;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.qiwx.pigeon.base.Constant.CHECK_BABY_DAYS;
import static com.qiwx.pigeon.base.Constant.CHECK_EGG_DAYS;
import static com.qiwx.pigeon.base.Constant.CHECK_KW_DAYS;
import static com.qiwx.pigeon.data.CageStatusConfig.CHECK_EGG_SHOUJING1;
import static com.qiwx.pigeon.data.CageStatusConfig.CHECK_EGG_SHOUJING2;
import static com.qiwx.pigeon.data.CageStatusConfig.CHECK_EGG_SHOUJING2SIJING1;
import static com.qiwx.pigeon.data.CageStatusConfig.CHECK_EGG_SHOUJING2WUJING1;
import static com.qiwx.pigeon.data.CageStatusConfig.CHECK_EGG_SIJING2;
import static com.qiwx.pigeon.data.CageStatusConfig.CHECK_EGG_WUDAN;
import static com.qiwx.pigeon.data.CageStatusConfig.CHECK_EGG_WUJING1;
import static com.qiwx.pigeon.data.CageStatusConfig.CHECK_EGG_WUJING2;
import static com.qiwx.pigeon.data.CageStatusConfig.PRODUCE_CZ2;
import static com.qiwx.pigeon.data.CageStatusConfig.PRODUCE_FD;

/**
 * @description
 * @Author qiwx
 * @Date 2020-03-28 14:14
 * sql查询工具
 **/
public class DBSqlUtil {
    public static List<WareHouseBean> wareHouses = new ArrayList<>();

    public synchronized static List<WareHouseBean> queryWareHouse() {
        wareHouses.clear();
        //查询正在使用的仓库
        List<WareHouseModel> list = LitePal.order("number").where("usestatus=?", "1").find(WareHouseModel.class);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                WareHouseBean bean = new WareHouseBean();
                bean.setId(list.get(i).getId());
//                bean.setName("鸽仓:" + list.get(i).getId());
                bean.setNumber(list.get(i).getNumber());
                bean.setName("鸽仓：" + bean.getNumber());
                bean.setStatus(list.get(i).getUseStatus());
                wareHouses.add(bean);
            }
        }

        return wareHouses;
    }


    //下蛋日期如果选择空窝选项，则将鸽笼设置成空窝，并将生产表记录清空
    public synchronized static boolean updateProdece(int wh_id, int cageNumber) {
        CageModel model = LitePal.where("wh_id=? and number=?", wh_id + "", cageNumber + "").findFirst(CageModel.class);
        //鸽笼必须是一对鸽的时候才可以操作
        if (model != null && model.getStatus() == CageStatusConfig.STATUS_YGYM) {
            //清空生产表
            DBSqlUtil.setCageKW(model, 0);
            model.setIs_remind(0);
            model.setIs_adjust(false);
            if (model.save()) {
                MyToast.showLong("该鸽笼设置空笼成功");
            } else {
                MyToast.showLong("操作失败");
            }
//
//            wh_id.setProduce_status(0);
//            if (wh_id.save()) {
//                MyToast.showLong(cageNumber + "号鸽笼已经置成空窝");
////                cbEmptyCages.setChecked(false);
//            }
            //TODO 删生统计信息
//            LitePal.deleteAll(SummaryFertilizeModel.class, "c_id=?", model.getId() + "");

            return true;
        } else {
            MyToast.showLong(cageNumber + "号鸽笼是:" + getStatusDes(model.getStatus()));
            return false;
        }
    }

    public synchronized static String getStatusDes(int status) {
        if (status == CageStatusConfig.STATUS_KL) {
            return "空笼状态";
        } else if (status == CageStatusConfig.STATUS_SM) {
            return "双母鸽状态";
        } else if (status == CageStatusConfig.STATUS_SG) {
            return "双公鸽状态";
        } else if (status == CageStatusConfig.STATUS_DZ) {
            return "单只鸽状态";
        } else if (status == CageStatusConfig.STATUS_DG) {
            return "单公鸽状态";
        } else if (status == CageStatusConfig.STATUS_DM) {
            return "单母鸽状态";
        } else if (status == CageStatusConfig.STATUS_PD) {
            return "配对中状态";
        } else {
            return "一公一母";

        }

    }

    public synchronized static String getProduceStatusDes(int status) {
        if (status == CageStatusConfig.PRODUCE_YD) {
            return "有蛋";
        } else if (status == CageStatusConfig.PRODUCE_CD) {
            return "查蛋";
        } else if (status == CageStatusConfig.PRODUCE_FD) {
            return "孵蛋";
        } else if (status == CageStatusConfig.PRODUCE_CZ) {
            return "查崽";
        } else if (status == CageStatusConfig.PRODUCE_CZ2) {
            return "重新查崽";
        } else if (status == CageStatusConfig.PRODUCE_CK) {
            return "出壳";
        } else if (status == CageStatusConfig.PRODUCE_KW) {
            return "空窝";
        } else {
            return "异常状态";

        }

    }

    //补录下蛋日期
    public synchronized static boolean saveLayEgg(int wh_id, String cageNumber, boolean isEmptyCage, boolean isBadEgg, boolean isLimit) {
        int c_number = 0;
        try {
            c_number = Integer.valueOf(cageNumber);
        } catch (Exception e) {
            e.printStackTrace();
        }
        boolean ifFudan = false;//默认孵蛋
        return saveLayEgg(wh_id, c_number, ifFudan, isBadEgg, isEmptyCage, 0, 0, isLimit);
    }
    /*
     * 下蛋确认操作
     *  isEmptyCage 设置成空窝
     *  isGoodEgg 是不是好蛋
     *  日常工段里直接点确定下蛋
     * */

    public synchronized static boolean saveLayEgg(int wh_id, String cageNumber, boolean isEmptyCage, boolean isBadEgg) {
        int c_number = 0;
        try {
            c_number = Integer.valueOf(cageNumber);
        } catch (Exception e) {
            e.printStackTrace();
        }
        boolean ifFudan = false;//默认孵蛋
        return saveLayEgg(wh_id, c_number, ifFudan, isBadEgg, isEmptyCage, 0, 0, true);
    }

    /*
     * fertilizetype 受精类型
     * isLimit 是否限制下蛋条件
     *
     * */
    public synchronized static boolean saveLayEgg(int wh_id, int cageNumber, boolean isFudan, boolean isBadEgg, boolean isEmptyCage, long layDate, int fertilizetype, boolean isLimit) {
        boolean isResult = false;
        //仓库id
        if (wh_id > 0) {
            CageModel model = LitePal.where("wh_id=? and number=?", wh_id + "", cageNumber + "").findFirst(CageModel.class);
            if (model == null) {
                MyToast.showLong("该鸽仓下没有此鸽笼");
            } else {
                int status = model.getStatus();//鸽笼状态
                if (status == CageStatusConfig.STATUS_YGYM) {
                    //空窝状态下才可以设置下蛋日期
                    int pStatus = model.getProduceStatus();//生产状态
                    //必须是空窝和一公一母状态
                    if (pStatus == CageStatusConfig.PRODUCE_KW) {
                        if (layDate > 0) {
                            // 判断下蛋日期不能早与存栏日期
                            long cl = model.getUpdate_date();
                            //TODO 先去掉
//                            if (layDate <= cl) {
//                                String clDate = DateTimeUtils.timeStamp2Date(cl);
//                                MyToast.showLong("下蛋日期不能早于存栏日期:" + clDate);
//                                return false;
//                            }
                            model.setLay_egg_date(layDate);
                        } else {
                            model.setLay_egg_date(DateTimeUtils.getCurrentStamp());
                        }
                        if (model.getLast_lay_egg_date() == 0) {
                            model.setLay_egg_date(model.getLay_egg_date());
                        }

                        //同一个鸽笼下蛋间隔必须大于5天
                        CageRecordModel cm = LitePal.where("c_id=?", model.getId() + "").findFirst(CageRecordModel.class);
                        if (cm != null && isLimit) {
                            long last = cm.getLay_egg_date();
                            long current = model.getLay_egg_date();
                            int days;
                            if (AppContext.isGoTimeByMinute) {
                                days = DateTimeUtils.differentMinute(new Date(last), new Date(current));
                            } else {

                                days = DateTimeUtils.differentDays(new Date(last), new Date(current));
                            }

                            if (days < Constant.LAY_EGG_CYCLE) {
                                MyToast.showLong("该鸽笼下蛋周期不足5天");
                                return false;
                            }
                        }
                        //
                        cm = new CageRecordModel();
                        cm.setC_id(model.getId());
                        cm.setC_number(model.getNumber());
                        cm.setWh_id(model.getWh_id());
                        cm.setLay_egg_date(model.getLay_egg_date());
                        cm.save();
                        // model.setProduce_status(CageStatusConfig.PRODUCE_YD);

                        //根据类型添加
                        saveShoujing(model, getFerilizeStatusByTpye(fertilizetype), isBadEgg);
                        //如果用户选择了空窝 则置成空窝
                        if (isEmptyCage) {
                            setCageKW(model, Constant.USER_ID);
                            isResult = updateProdece(wh_id, cageNumber);
                        } else {
                            //根据下蛋日期计算蛋的状态
                            int days = DateTimeUtils.differentDays(new Date(model.getLay_egg_date()), new Date());
                            //如果用户选择了孵蛋操作，直接把状态设置成孵蛋
                            if (isFudan) {
                                status = PRODUCE_FD;
                            } else {
                                status = getEggStatusByDays(model, days);
                            }
                            model.setProduceStatus(status);

                        }
                        if (model.save()) {
                            MyToast.showLong(cageNumber + "号鸽笼操作成功");
                            updateCageStatus(model, Constant.USER_ID);

                            isResult = true;
                        } else {
                            MyToast.showLong(cageNumber + "号鸽笼操作失败");
                        }
                    } else {
                        if (isEmptyCage) {
                            setCageKW(model, Constant.USER_ID);
                            if (model.save()) {
                                MyToast.showLong("操作成功");
                                updateCageStatus(model, Constant.USER_ID);

                            }


                        } else {
                            MyToast.showLong(cageNumber + "号鸽笼不是空窝状态");

                        }
                    }

                } else {
                    MyToast.showLong(cageNumber + "号鸽笼不是存栏状态");
                }

            }

        } else {
            MyToast.showLong("请选择鸽仓");

        }
        return isResult;
    }

    //设施鸽笼空窝
    public synchronized static void setCageKW(CageModel model, int userId) {
        //保存上次下蛋日期
        model.setLast_lay_egg_date(model.getLay_egg_date());
        model.setLay_egg_date(0);
        model.setKw_date(DateTimeUtils.getCurrentStamp());
        model.setProduceStatus(CageStatusConfig.PRODUCE_KW);
//        updateCageStatus(model,userId);
    }

    //统计出壳情况
    public synchronized static void saveChuKe(CageModel model, int ckamount) {
        int c_id = model.getId();
        int wh_id = model.getWh_id();
        long layDate = model.getLay_egg_date();
        long cl_date = model.getUpdate_date();
        //此鸽笼状态必须大于孵蛋状态才可以统计出壳
        if (model.getProduceStatus() >= CageStatusConfig.PRODUCE_FD) {
            SummaryPigeonCKModel spc = LitePal.where("c_id=?", c_id + "").findFirst(SummaryPigeonCKModel.class);
            if (spc == null || layDate != spc.getLay_egg_date()) {
                spc = new SummaryPigeonCKModel();
                spc.setWh_id(wh_id);
                spc.setC_id(c_id);
                spc.setLay_egg_date(layDate);
                spc.setCage_cl_date(cl_date);
                spc.setC_number(model.getNumber());
                spc.setCk_date(DateTimeUtils.getCurrentStamp());
            }
            spc.setAmount(ckamount + spc.getAmount());


//            SummaryFertilizeModel sem = LitePal.where("c_id=?", c_id + "").findFirst(SummaryFertilizeModel.class);
//            if (sem == null || layDate != sem.getLay_egg_date()) {
//                sem = new SummaryFertilizeModel();
//                sem.setCage_date(model.getUpdate_date());
//                sem.setAmount(1);
//                sem.setC_id(c_id);
//                sem.setC_number(model.getNumber());
//                sem.setWh_id(wh_id);
//                sem.setLay_egg_date(layDate);
//            }
//            //sem.setAmount(getAmountByEggStatus(status));
//            sem.setOpreateTime(DateTimeUtils.getCurrentStamp());
//            if (ckamount >= 0) {
//                int nowAmount = sem.getChukeAmount();
//                sem.setChukeAmount(nowAmount + ckamount);
//            } else {
//                //如果ckamount 为负数则代表是无蛋无仔 转成正书存储
//                sem.setWdwzAmount(Math.abs(ckamount));
//            }
            //
            if (spc.save()) {
                MyToast.showLong("操作成功");
            } else {
                MyToast.showLong("操作失败");
            }
        } else {
            MyToast.showLong("鸽笼状态不是孵蛋状态，不可以操作出壳。");
        }


    }

    //统计下蛋受精情况
    public synchronized static void saveShoujing(CageModel model, int status, boolean isBadEgg) {
        int c_id = model.getId();
        int wh_id = model.getWh_id();
        long layDate = model.getLay_egg_date();
        //将无蛋统计到蛋受精情况
        SummaryFertilizeModel sem = LitePal.where("c_id=?", c_id + "").findFirst(SummaryFertilizeModel.class);
        if (sem == null || layDate != sem.getLay_egg_date()) {
            sem = new SummaryFertilizeModel();
            sem.setAmount(1);
            sem.setC_id(c_id);
            sem.setC_number(model.getNumber());
            sem.setWh_id(wh_id);
            sem.setCage_date(model.getUpdate_date());
            sem.setLay_egg_date(layDate);
            sem.setOpreateTime(DateTimeUtils.getCurrentStamp());
        }
        if (isBadEgg) {
            sem.setBadAmount(1);
        }
        //根据不同状态转换成下蛋数
        //sem.setAmount(getAmountByEggStatus(status));
        if (status >= 0) {
            sem.setEgg_status(status);
        }
        if (sem.save()) {
            MyToast.showLong("操作成功");
        } else {
            MyToast.showLong("操作失败");
        }


    }

    //根据用户选择的受精类型 选择 添加对应值
    public synchronized static int getFerilizeStatusByTpye(int rbId) {
        int status = 0;
        switch (rbId) {
            case R.id.rb_shouj2:
                // produceModel.setFertilizeed_egg(2);
                status = CHECK_EGG_SHOUJING2;
                break;
            case R.id.rb_sij2:
                status = CHECK_EGG_SIJING2;

                //produceModel.setDeath_fertilize_egg(2);
                break;
            case R.id.rb_wuj2:
                status = CHECK_EGG_WUJING2;

                //produceModel.setNo_fertilize_egg(2);
                break;
            case R.id.rb_shou2wuj1:
                status = CHECK_EGG_SHOUJING2WUJING1;

                //produceModel.setFertilizeed_egg(1);
                //produceModel.setNo_fertilize_egg(1);
                break;
            case R.id.rb_shou2sij1:
                status = CHECK_EGG_SHOUJING2SIJING1;

                //produceModel.setFertilizeed_egg(1);
                //produceModel.setDeath_fertilize_egg(1);
                break;
            case R.id.rb_wudan:
                status = CHECK_EGG_WUDAN;

                //1表示无蛋
                //produceModel.setNo_egg(1);
                break;
            case R.id.rb_shouj1:
                status = CHECK_EGG_SHOUJING1;

                break;
            case R.id.rb_wujing1:
                status = CHECK_EGG_WUJING1;

                break;
        }
        return status;

    }

    //判断当前鸽笼是不是存在
    public synchronized static CageModel checkCageIdexist(int wh_id, String cagemoelId) {

        if (TextUtils.isEmpty(cagemoelId)) {
            MyToast.showLong("鸽笼编号不能为空");
            return null;
        }
        int cageId = 0;
        try {
            cageId = Integer.valueOf(cagemoelId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (cageId <= 0) {
            MyToast.showLong("鸽笼编号错误");
            return null;
        }
        CageModel model = LitePal.where("wh_id=? and number=?", wh_id + "", cageId + "").findFirst(CageModel.class);
        if (model == null) {
            MyToast.showLong("该鸽仓下没有此鸽笼");
            return null;
        }
        return model;
    }

    public synchronized boolean isCageExist(int c_id) {
        return LitePal.isExist(CageModel.class, "id=?", c_id + "");
    }

    //鸽子死亡，向鸽子死亡统计表中添加数据
    public synchronized static void addPigeonDeath() {

    }

    //查询受精表情况，并返回数据
    public synchronized static String getFertifizeConditions() {
        String shouj2 = String.format("count(egg_status=%d or null) as shouj2", CageStatusConfig.CHECK_EGG_SHOUJING2);
        String sij2 = String.format("count(egg_status=%d or null) as sij2", CageStatusConfig.CHECK_EGG_SIJING2);
        String wuj2 = String.format("count(egg_status=%d or null) as wuj2", CageStatusConfig.CHECK_EGG_WUJING2);
        String s2wj1 = String.format("count(egg_status=%d or null) as s2wj1", CageStatusConfig.CHECK_EGG_SHOUJING2WUJING1);
        String s2sj1 = String.format("count(egg_status=%d or null) as s2sj1", CageStatusConfig.CHECK_EGG_SHOUJING2SIJING1);
        String wudan = String.format("count(egg_status=%d or null) as wudan", CageStatusConfig.CHECK_EGG_WUDAN);
//        String bufudan = String.format("count(egg_status=%d or null) as bufudan", CageStatusConfig.CHECK_EGG_BUFUDAN);
//        String broken = String.format("count(egg_status=%d or null) as broken", CageStatusConfig.CHECK_EGG_BROKEN);

        StringBuffer sb = new StringBuffer();
        sb.append(",").append(shouj2);
        sb.append(",").append(sij2);
        sb.append(",").append(wuj2);
        sb.append(",").append(s2wj1);
        sb.append(",").append(s2sj1);
        sb.append(",").append(wudan);
//        sb.append(",").append(bufudan);
//        sb.append(",").append(broken);
        return sb.toString();
    }

    public synchronized static int getEggStatusByDays(CageModel model, int days) {
        if (days >= CHECK_KW_DAYS) {
            return CageStatusConfig.PRODUCE_KW;
        } else if (days >= CHECK_BABY_DAYS) {
            if (model.getProduceStatus() == PRODUCE_CZ2)
                return CageStatusConfig.PRODUCE_CZ2;
            return CageStatusConfig.PRODUCE_CZ;
        } else if (days >= CHECK_EGG_DAYS) {
            if (model.getProduceStatus() == PRODUCE_FD)
                return CageStatusConfig.PRODUCE_FD;
            return CageStatusConfig.PRODUCE_CD;
        } else {
            return CageStatusConfig.PRODUCE_YD;
        }
    }

    //将鸽笼状态设置成空笼
    public synchronized static void setCageKL(CageModel model, boolean isSave) {
        if (model == null)
            return;
        setKLHistory(model);
        long current = DateTimeUtils.getCurrentStamp();
        model.setStatus(CageStatusConfig.STATUS_KL);
        model.setProduceStatus(CageStatusConfig.PRODUCE_KW);
        model.setKw_date(current);
        model.setLast_lay_egg_date(0);

        model.setUpdate_date(current);
        if (isSave) {
            model.save();
            updateCageStatus(model, Constant.USER_ID);
        }

    }

    //将相关统计类制成历史记录
    public synchronized static void setKLHistory(CageModel model) {
        if (model == null)
            return;
        //受精相关
        ContentValues contentValues = new ContentValues();
        contentValues.put("is_history", 1);

        LitePal.updateAll(SummaryFertilizeModel.class, contentValues, "c_id=? and cage_date=?", model.getId() + "", model.getUpdate_date() + "");
        LitePal.updateAll(SummaryNoEggModel.class, contentValues, "c_id=? and cage_date=?", model.getId() + "", model.getUpdate_date() + "");
        LitePal.updateAll(SummaryPigeonDeathModel.class, contentValues, "c_id=? and cage_date=?", model.getId() + "", model.getUpdate_date() + "");
    }


    public synchronized static void setCageCL(CageModel model, boolean isSave) {
        if (model == null)
            return;
        long current = DateTimeUtils.getCurrentStamp();
        model.setStatus(CageStatusConfig.STATUS_YGYM);
        model.setProduceStatus(CageStatusConfig.PRODUCE_KW);

        model.setKw_date(current);
        model.setUpdate_date(current);
        model.setIs_adjust(false);
        model.setIs_remind(0);
        model.setLay_egg_date(0);
        if (isSave) {
            model.save();
            updateCageStatus(model, Constant.USER_ID);
        }
    }

    //更新鸽笼状态
    public synchronized static void updateCageStatus(CageModel model, int opreate_userid) {
        String c_id = model.getId() + "";
        String lay_egg_date = model.getLay_egg_date() + "";
        String produce_status = model.getProduceStatus() + "";
        CageStatusRecord csr = LitePal
                .where("c_id=? and lay_egg_date=? and produce_status=?", c_id, lay_egg_date, produce_status)
                .findFirst(CageStatusRecord.class);
        if (csr == null) {
            csr = new CageStatusRecord();
            csr.setC_id(model.getId());
            csr.setWh_id(model.getWh_id());
            csr.setC_number(model.getNumber());
            csr.setLay_egg_date(model.getLay_egg_date());
            csr.setProduce_status(model.getProduceStatus());
            csr.setOpreate_user_id(opreate_userid);
            csr.setOperate_time(DateTimeUtils.getCurrentStamp());
            csr.save();
        }


    }


}
